package logic

import (
	"context"
	"errors"
	"fmt"
	"video-up-manager/models/cache"
	"video-up-manager/models/mysql"
	"video-up-manager/pkg"

	"video-up-manager/videorpc/internal/svc"
	"video-up-manager/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	if len(in.PhoneNum) != 11 && in.PhoneNum != "123" {
		return nil, errors.New("请输入正确的手机号")
	}
	if in.TypeLogin == 3 {
		if err := user.FindUserByPhoneNum(mysql.DB, in.PhoneNum); err == nil {
			return nil, errors.New("该手机号已注册，可直接登录")
		}
		user := mysql.User{
			Model:      gorm.Model{},
			PhoneNum:   in.PhoneNum,
			Pwd:        pkg.Md5(in.Pwd),
			NickName:   fmt.Sprintf("游客_%s", in.PhoneNum[:7]),
			AvatarLink: "http://t4kano60z.hn-bkt.clouddn.com/3m.jpg",
		}
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()
		if result != in.SendSmsCode {
			return nil, errors.New("验证码错误")
		}
		if err := user.UserAdd(mysql.DB); err != nil {
			return nil, errors.New("注册失败")
		}
	}
	if err := user.FindUserByPhoneNum(mysql.DB, in.PhoneNum); err != nil {
		return nil, errors.New("手机号不存在")
	}
	if in.TypeLogin == 1 {
		if user.Pwd != pkg.Md5(in.Pwd) {
			return nil, errors.New("密码错误")
		}
		if user.AccountStatus == "1" {
			return nil, errors.New("账号已禁用，请联系管理员")
		}
	}
	if in.TypeLogin == 2 {
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()
		if result != in.SendSmsCode {
			return nil, errors.New("验证码错误")
		}
		if result == "" {
			return nil, errors.New("验证码已过期，请重新获取")
		}
	}
	if in.TypeLogin == 4 {
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()
		if result != in.SendSmsCode {
			return nil, errors.New("验证码错误")
		}
		if user.Pwd != pkg.Md5(in.Pwd) {
			return nil, errors.New("原密码错误")
		}
		if in.NewPwd != in.New2Pwd {
			return nil, errors.New("两次出输入密码不一致")
		}
		user.Pwd = pkg.Md5(in.NewPwd)
		if err := user.UserUpdate(mysql.DB, in.PhoneNum); err != nil {
			return nil, errors.New("密码重置失败")
		}
		fmt.Println("密码已重置成功")
	}
	return &videorpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
